<template>
  <div class="minio-viewer-container">
    <!-- 关闭按钮 -->
    <el-button class="close-btn" @click="handleClose" icon="el-icon-close" circle />

    <!-- 加载状态显示 -->
    <div v-if="loading" class="loading-container">
      <el-progress type="circle" :percentage="50" :status="loadingStatus"></el-progress>
      <p>{{ loadingText }}</p>
    </div>

    <!-- OnlyOffice 查看器组件 -->
    <only-office-viewer v-if="showViewer" :file-url="fileUrl" :file-name="fileName" :editable="editable"
      :user="currentUser" />

    <!-- 错误状态显示 -->
    <div v-if="error" class="error-container">
      <el-alert :title="error" type="error" show-icon></el-alert>
      <el-button @click="retryLoading">重试</el-button>
    </div>
  </div>
</template>

<script>
import OnlyOfficeViewer from './onlyOfficeViewer.vue';

export default {
  name: 'MinIOViewer',
  components: {
    OnlyOfficeViewer
  },
  props: {
    previewFile: {
      type: Object,
      required: true,
      default: () => ({}),
      validator: (value) => {
        return value.filePath && value.id; // 确保必要字段存在
      },
    },
    // 是否可编辑 (默认为只读)
    editable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      loading: true,
      loadingStatus: 'success',
      loadingText: '正在加载文档...',
      showViewer: false,
      error: '',
      fileUrl: '',
      fileName: '',
      currentUser: {
        id: this.$store.state.user.id,
        name: this.$store.state.user.name,
      }
    }
  },
  created() {
    this.initViewer();
  },
  methods: {
    async initViewer() {
      try {
        this.loading = true;
        this.error = '';

        // 获取文件路径
        this.fileUrl = this.previewFile.filePath;
        this.fileName = this.previewFile.name;
        
        this.showViewer = true;   //打开onlyOffce
        this.loading = false;     //关闭加载
      } catch (err) {
        console.error('初始化OnlyOffice失败:', err);
        this.error = '加载文档失败: ' + (err.message || '未知错误');
        this.loadingStatus = 'exception';
        this.loadingText = '加载失败';
        this.showViewer = false;
      }
    },

    handleClose() {
      this.$emit('onlyOfficeClose');
    },

    retryLoading() {
      this.error = '';
      this.initViewer();
    }
  }
}
</script>

<style scoped>
.minio-viewer-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 20px;
}

.close-btn {
  position: absolute;
  right: 35px;
  top: 15px;
  z-index: 1000;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.error-container {
  text-align: center;
}

.error-container .el-alert {
  margin-bottom: 20px;
  max-width: 80%;
}
</style>
